package com.boco.modules.fdoc.api;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import redis.clients.jedis.exceptions.JedisConnectionException;
import sun.misc.BASE64Decoder;

import com.boco.common.enums.ApiStatusEnum;
import com.boco.common.json.BaseJsonVo;
import com.boco.common.sms.SmsRandom;
import com.boco.common.utils.JsonUtils;
import com.boco.common.utils.MatcherUtiles;
import com.boco.common.utils.StringUtils;
import com.boco.common.web.BaseController;
import com.boco.modules.fdoc.model.DoctorEntity;
import com.boco.modules.fdoc.model.UserEntity;
import com.boco.modules.fdoc.service.CommonService;
import com.boco.modules.fdoc.service.DocService;
import com.boco.modules.fdoc.service.UserService;
import com.boco.modules.fdoc.vo.DoctorDetailVo;
import com.boco.modules.fdoc.vo.DoctorUserVo;
import com.boco.modules.fdoc.vo.UserVo;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;

/**
 * 用户 api
 * 
 * @author sufj
 *
 */
@RestController
@RequestMapping(value = "/user", produces = "text/json;charset=UTF-8")
public class UserApi extends BaseController {

	@Resource
	CommonService commonService;
	@Resource
	UserService userService;
	@Resource
	DocService docService;

	@RequestMapping(value = "/getUser", method = RequestMethod.GET)
	@ApiOperation(value = "获取用户详细信息", notes = "{'uid':'用户唯一标识'}", response = UserVo.class)
	public String getUser(@RequestParam String uid) {
		//UserVo vo = new UserVo();
		
		UserEntity user = userService.getUser(uid);
		//BeanUtils.copyProperties(userService.getUser(uid), vo);
		//vo = (UserVo) user;
		return JsonUtils.getJson(BaseJsonVo.success(user));
	}

	@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
	@ApiOperation(value = "修改用户信息", notes = "{'uid':'用户uid','nickname':'昵称'," + "'realName':'真实姓名',"
			+ "'idCard':'身份证号'," + "'sex':'性别'," + "'height':'身高'," + "'weight':'体重',"
			+ "'address':'家庭住址','birthday':'出生年月','headImg':'图片base64字符串','strName':'图片名'}}", response = BaseJsonVo.class)
	public String updateUser(@RequestBody String userBody, HttpServletRequest request) {
		UserVo vo = JsonUtils.getObject(userBody, UserVo.class);
		//验证身份证号是否合法
		if (!MatcherUtiles.idCardMach(vo.getIdCard())) {
			return JsonUtils.getJson(BaseJsonVo.empty(ApiStatusEnum.IDCARD_OUTLAW.getKey(), ApiStatusEnum.IDCARD_OUTLAW.getValue()));
		}
		vo.setUpdateTime(new Date());
		/**
		 * 上传图片开始
		 */
		try {
			String headImg = vo.getHeadImg();
			String strName = vo.getStrName();
			if (headImg != null && !"".equals(headImg)) {
				String path = request.getSession().getServletContext()
						.getRealPath("upload"+System.getProperty("file.separator")+"img")
						+ System.getProperty("file.separator");
				BASE64Decoder decoder = new BASE64Decoder();
				// Base64解码
				byte[] b = decoder.decodeBuffer(headImg);
				for (int i = 0; i < b.length; ++i) {
					if (b[i] < 0) {// 调整异常数据
						b[i] += 256;
					}
				}
				// 生成jpeg图片
				String headSuffix = StringUtils.getSuffix(strName); // 获取后缀名
				String signImgHeadName = UUID.randomUUID().toString()
						.substring(0, 8)
						+ "." + headSuffix; // 重命名为8位随机数
				String localPathHead = path + signImgHeadName;
				File headPathHead = new File(path);// 获取文件夹路径
				if (!headPathHead.exists()) {// 判断文件夹是否创建，没有创建则创建新文件夹
					headPathHead.mkdirs();
				}

				OutputStream out = new FileOutputStream(localPathHead);
				out.write(b);
				out.flush();
				out.close();
				vo.setImg((request.getContextPath() + "/upload/img/"
						+ signImgHeadName).substring(9));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		userService.updateUser(vo);
		return JsonUtils.getJson(BaseJsonVo.success(userService.getUser(vo.getUid())));
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ApiOperation(value = "手机号加密码或者验证码登录", notes = "{'mobile':'手机号码','password':'密码','code':'验证码'}", response = UserVo.class)
	@ApiResponses(value = { @ApiResponse(code = 200, message = "成功"),
			@ApiResponse(code = 2010, message = "登录失败，手机号或密码错误"), @ApiResponse(code = 2011, message = "用户不存在") })
	public String login(@RequestBody String userBody) {
		System.out.println(userBody);
		// 1- 获取用户的手机号和验证码
		UserVo vo = JsonUtils.getObject(userBody, UserVo.class);

		// 2- 调用 commonService
		BaseJsonVo jsonVo = commonService.login(vo);

		// 3- 返回登陆结果
		return JsonUtils.getJson(jsonVo);
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ApiOperation(value = "手机注册", notes = "{'mobile':'手机号码','password':'密码','signUser':'用户类型','code':'验证码'}", response = UserVo.class)
	@ApiResponses(value = { @ApiResponse(code = 200, message = "成功"), @ApiResponse(code = 2021, message = "验证码错误"),
			@ApiResponse(code = 2022, message = "验证码无效") })
	public String register(@RequestBody String userBody) {
		try {

			UserVo vo = JsonUtils.getObject(userBody, UserVo.class);
			//验证手机号是否合法
			if (!MatcherUtiles.mobileMach(vo.getMobile())) {
				return JsonUtils.getJson(BaseJsonVo.empty(ApiStatusEnum.MOBILE_OUTLAW.getKey(), ApiStatusEnum.MOBILE_OUTLAW.getValue()));
			}
			//判断密码是否合法
			if (!MatcherUtiles.noSpecialChar((vo.getPassword()))) {
				return JsonUtils.getJson(BaseJsonVo.empty(ApiStatusEnum.PASSWORD_OUTLAW.getKey(), ApiStatusEnum.PASSWORD_OUTLAW.getValue()));
			}
			vo.setType("1");
			return JsonUtils.getJson(commonService.register(vo));

		} catch (Exception e) {
			logger.error("传入的JSON是：", userBody);
			e.printStackTrace();
			return JsonUtils.getJson(BaseJsonVo.error());
		}
	}

	@RequestMapping(value = "/getCaptcha", method = RequestMethod.GET)
	@ApiOperation(value = "验证码", notes = "{}", response = BaseJsonVo.class)
	public String getCaptcha() {
		String smsRandom = SmsRandom.createRandom();// 获取随机码
		return JsonUtils.getJson(BaseJsonVo.success(smsRandom));
	}

	@RequestMapping(value = "/sendSmsCode", method = RequestMethod.GET)
	@ApiOperation(value = "发送手机验证码", notes = "{'mobile':'手机号'}", response = BaseJsonVo.class)
	public String sendSmsCode(@RequestParam String mobile) {
		return JsonUtils.getJson(commonService.sendPhoneCode(mobile));
	}

	@RequestMapping(value = "/forgotPassword", method = RequestMethod.POST)
	@ApiOperation(value = "找回密码", notes = "{'mobile':'手机号','password':'密码','code':'验证码'}", response = BaseJsonVo.class)
	public String forgotPassword(@RequestBody String userBody) {
		UserVo vo = JsonUtils.getObject(userBody, UserVo.class);
		//验证手机号是否合法
		if (!MatcherUtiles.mobileMach(vo.getMobile())) {
			return JsonUtils.getJson(BaseJsonVo.empty(ApiStatusEnum.MOBILE_OUTLAW.getKey(), ApiStatusEnum.MOBILE_OUTLAW.getValue()));
		}
		//判断密码是否合法
		if (!MatcherUtiles.noSpecialChar((vo.getPassword()))) {
			return JsonUtils.getJson(BaseJsonVo.empty(ApiStatusEnum.PASSWORD_OUTLAW.getKey(), ApiStatusEnum.PASSWORD_OUTLAW.getValue()));
		}
		// 找回密码，手机验证码暂时未加入验证
		int returnNum = userService.forgotPsw(vo);
		
		if (returnNum == 0) {
			return JsonUtils.getJson(BaseJsonVo.empty(ApiStatusEnum.NONE_CHANGED.getKey(), ApiStatusEnum.NONE_CHANGED.getValue()));
		}else {
			return JsonUtils.getJson(BaseJsonVo.success(returnNum));
		}
	}

	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	@ApiOperation(value = "修改密码", notes = "{uid:uid,password:password,newPassword:newPassword}", response = BaseJsonVo.class)
	public String updatePassword(@RequestBody String userBody) {
		UserVo vo = JsonUtils.getObject(userBody, UserVo.class);
		//判断新密码是否合法
		if (!MatcherUtiles.noSpecialChar((vo.getNewPassword()))) {
			return JsonUtils.getJson(BaseJsonVo.empty(ApiStatusEnum.PASSWORD_OUTLAW.getKey(), ApiStatusEnum.PASSWORD_OUTLAW.getValue()));
		}
		int i = userService.updatePassword(vo);
		
		return JsonUtils.getJson(BaseJsonVo.success(i));
	}

	@RequestMapping(value = "/updateMobile", method = RequestMethod.POST)
	@ApiOperation(value = "绑定手机号", notes = "{uid:uid,mobile:mobile}", response = BaseJsonVo.class)
	public String updateMobile(@RequestBody String userBody) {
		UserVo vo = JsonUtils.getObject(userBody, UserVo.class);
		//验证手机号是否合法
		if (!MatcherUtiles.mobileMach(vo.getMobile())) {
			return JsonUtils.getJson(BaseJsonVo.empty(ApiStatusEnum.MOBILE_OUTLAW.getKey(), ApiStatusEnum.MOBILE_OUTLAW.getValue()));
		}
		int i = userService.updateMobile(vo);
		
		return JsonUtils.getJson(BaseJsonVo.success(i));
	}
	
	@RequestMapping(value = "/doctorLogin", method = RequestMethod.POST)
	@ApiOperation(value = "手机号码登录（医生端）", notes = "{'mobile':'手机号码','password':'密码','code':'验证码'}", response = UserVo.class)
	public String doctorLogin(@RequestBody String userBody) {
		// 1- 获取用户的手机号和验证码
		UserVo vo = JsonUtils.getObject(userBody, UserVo.class);
		vo.setSignUser(2);
		// 2- 调用 commonService
		DoctorUserVo docUserVo = null;
		try {
			docUserVo =	commonService.doctorLogin(vo);
		} catch (BeanCreationException e) {
			return JsonUtils.getJson(BaseJsonVo.empty(ApiStatusEnum.DUBBO_ERROR.getKey(), ApiStatusEnum.DUBBO_ERROR.getValue()));
		} catch (JedisConnectionException e) {
			return JsonUtils.getJson(BaseJsonVo.empty(ApiStatusEnum.REDIS_ERROR.getKey(), ApiStatusEnum.REDIS_ERROR.getValue()));
		}
		if (docUserVo == null) {   //返回值为空，说明没有查询到用户，返回用户名或密码错误
			return JsonUtils.getJson(BaseJsonVo.empty(ApiStatusEnum.LOGIN_ERROR.getKey(), ApiStatusEnum.LOGIN_ERROR.getValue()));
		}else {
			DoctorEntity docEntity = docService.getDocByDocUid(docUserVo.getUid());
			if (docEntity != null) {
				DoctorDetailVo detailVo = docService.getDoctorDetail(docEntity.getId());
				//设置医生信息
				docUserVo.setTitle(detailVo.getTitle());
				docUserVo.setDeptId(detailVo.getDeptId());
				docUserVo.setHospId(detailVo.getHospId());
				docUserVo.setSkill(detailVo.getSkill());
				docUserVo.setDetail(detailVo.getDetail());
				docUserVo.setStar(detailVo.getStar());
				docUserVo.setDescription(detailVo.getDescription());
				docUserVo.setHospName(detailVo.getHospName());
				docUserVo.setDeptName(detailVo.getDeptName());
				docUserVo.setGoodComment(detailVo.getGoodComment());
				docUserVo.setBookingNum(detailVo.getBookingNum());
				docUserVo.setAllEvaluateNum(detailVo.getAllEvaluateNum());
				docUserVo.setGoodEvaluateNum(detailVo.getGoodEvaluateNum());
				docUserVo.setGeneralEvaluateNum(detailVo.getGeneralEvaluateNum());
				docUserVo.setBadEvaluateNum(detailVo.getBadEvaluateNum());
			}
			return JsonUtils.getJson(BaseJsonVo.success(docUserVo));
		}
		// 3- 返回登陆结果
	}

}
